from urllib import request, parse
import json


def translate(kw):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom='
    data = {'i': kw,
            'rom': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTIME',
            'typoResult': 'true'
            }
    data = parse.urlencode(data)
    headers = {'Content-Length': len(data),
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
               }
    try:
        req = request.Request(url, data=bytes(data, encoding="utf-8"), headers=headers)
        res = request.urlopen(req)
        str_json = res.read().decode('utf-8')

        # print(str_json)

        myjson = json.loads(str_json)

        print(myjson['translateResult'][0][0]['tgt'])
    except:
        print('error.')


if __name__ == '__main__':
    while True:
        yourkw = input('请输入翻译内容：')
        if yourkw == 'q':
            break
        translate(yourkw)
